package com.mattemanouil.DriveAway;

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.telephony.SmsManager; 
import android.telephony.SmsMessage; 
 
public class SMSReceiver extends BroadcastReceiver { 
 
	
     private SharedPreferences prefs; 
      
     @Override 
     public void onReceive(Context context, Intent intent) { 
    	 
    	 
           
          prefs = PreferenceManager.getDefaultSharedPreferences(context); 
          
          //Toast toast1=Toast.makeText(context, "Incoming Message", Toast.LENGTH_LONG);
    	  //toast1.show();
    	  
          if(prefs.getString("awayMessageListPreference", "Please select an away message.").equals("No away message")) { 
               // If the away message is set to no away message, nothing needs to be done. 
        	  //Toast toast2=Toast.makeText(context, "Incoming Message", Toast.LENGTH_LONG);
        	  //toast2.show();
          } 
          else { 
                Bundle bundle = intent.getExtras(); 
 
               Object messages[] = (Object[]) bundle.get("pdus"); 
               SmsMessage smsMessage[] = new SmsMessage[messages.length]; 
                
               for (int n = 0; n < messages.length; n++) { 
                    smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); 
               } 
 
               // show first message 
              // Toast toast = Toast.makeText(context, "In receiver: " + smsMessage[0].getDisplayOriginatingAddress(), duration); 
               //toast.show(); 
                
               SmsManager sm = SmsManager.getDefault(); 
               String number = smsMessage[0].getDisplayOriginatingAddress(); 
                
               SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
                
               sm.sendTextMessage(number, null, prefs.getString("awayMessageListPreference", "0"), null, null); 
                               
               //Toast toast3 = Toast.makeText(context, "Sent SMS: " + smsMessage[0].getDisplayOriginatingAddress(), duration); 
               //toast3.show(); 
          } 
                     
     } 
      
}  